<template>
    <div class="allmap" :id="defaultOptions.el"></div>
</template>
<script>
import baiduMap, { MBMap } from '@/common/js/baiduMap'
export default ({
    props: {
        options: Object,
        model: Object,
        getPoint: String
    },
    data() {
        return {
            defaultOptions: {
                ak: 'sI8DTCFVcQuQIU2wXo8OWGu6',
                el: 'allmap'
            },
            mBMap: null
        }
    },
    methods: {
        callback: function(res) {
            this.$emit('update', res)
        },
        setMarker(address) {
            if (address && this.mBMap) {
                this.mBMap.getPoint(address)
            }
        },
        async createdMap(callback) {
            try {
                if (this.mBMap) {
                    callback()
                } else {
                    const { ak, el } = this.defaultOptions
                    const cb = this.callback
                    await baiduMap(ak)
                    this.mBMap = new MBMap({
                        el,
                        cb
                    })
                    callback()
                }
            } catch (error) {
                this.$message.error(`${error}`)
            }
        }
    },
    watch: {
        "options": {
            immediate: true,
            handler: function(val, oldVal) {
                if (val) {
                    this.defaultOptions = { ...this.defaultOptions, ...val }
                }
            }
        },
        "model": {
            immediate: true,
            handler: function(val, oldVal) {
                this.createdMap(() => {
                    if (val && val.point) {
                        this.mBMap.setData(val)
                        this.mBMap.addMarker(val.point, true)
                    } else {
                        this.mBMap.setData({
                            title: '',
                            content: '',
                            point: null
                        })
                        this.mBMap.clearMarker(true)
                    }
                })
            }
        }
    }
})
</script>
<style lang="scss" scoped>
.allmap /deep/ {
    width: 100%;
    height: 100%;
    min-width: 300px;
    min-height: 300px;
    .anchorBL { display: none; }
}
</style>